import java.io.*;
import java.lang.reflect.Field;
import java.nio.ByteBuffer;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.Random;

public class Main {
    public static void main(String[] args) throws IOException {
        Random random = new Random();

        /**
         * 创建200个文件
         */
        int count = 0;
        while(count < 200) {
            File file = new File("D:\\text\\" + random.nextInt(1,701) +".txt");
            if(file.createNewFile()) count++;
        }
        /**
         * 读取文件内容
         */
        BufferedReader read = new BufferedReader(new FileReader(new File("D:\\data.txt")));
        String value = read.readLine();
        int len = value.length();
        // 获取创建的txt 文件
        File file = new File("D:\\text");
        File[] files = file.listFiles();
        // 遍历获取到的文件
        for(File f: files) {
            String nameS = f.getName();// 获取文件名字
            String name = nameS.replaceAll(".txt","");// 字符串切割，拿下文件名字
            FileWriter writer = new FileWriter(f);// 写入文字

            int nameInt = Integer.valueOf(name);
            String str = value.substring(nameInt,nameInt + 100);
            // 这里写入成功了
            // 接下来链接数据库写入
            try {
                Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
                Connection connection = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;DatabaseName=text", "sa", "123456");
                String sql = "insert into demo (name,value) values (?,?)";

                // 指令预处理
                PreparedStatement statement = connection.prepareStatement(sql);
                statement.setInt(1,nameInt);
                statement.setString(2,str);
                // 获取结果集
                int ret = statement.executeUpdate();
                System.out.println("被修改行数: " + ret);
            } catch (Exception e) {
                e.printStackTrace();
            }
            // 到这里写入数据库成功了，接下来就是,关闭流了
            writer.write(str);
            writer.close();
        }
        System.out.println("ok");
    }
}